namespace SimpleWebServices.Web.UI.Html.Elements
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("input")]
    public class ImageInput : Input, IXmlSerializable
    {
        public ImageInput()
        {
        }

        public ImageInput(Name id)
            : base(id)
        {
        }

        public Uri Source
        {
            get;
            set;
        }

        public override string Type
        {
            get
            {
                return "image";
            }
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if ("input".Equals(name, StringComparison.OrdinalIgnoreCase) && this.Type.Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                result = xml.Deserialize<ImageInput>();
            }

            return result;
        }

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);

            if (XmlNodeType.Element == reader.NodeType)
            {
                string value = reader.GetAttribute("src");
                if (!string.IsNullOrEmpty(value))
                {
                    this.Source = new Uri(value);
                }
            }
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);

            if (null != this.Source)
            {
                writer.WriteAttributeString("src", this.Source.IsAbsoluteUri ? this.Source.AbsoluteUri : this.Source.OriginalString);
            }
        }
    }
}